package com.zhentao.controller;

import ch.qos.logback.classic.Logger;
import com.zhentao.service.ChatMessageService;
import com.zhentao.vo.Result;
import com.zhentao.websocket.pojo.ChatMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/chat")
public class ChatController {

    @Autowired
    private ChatMessageService chatMessageService;

    /**
     * 获取聊天记录（通过用户名）
     */
    @GetMapping("/messages")
    public Result<Map<String, Object>> getChatMessages(
//            @RequestParam(required = false) String user1,
//            @RequestParam(required = false) String user2,
            @RequestParam(required = false) String user1Id,
            @RequestParam(required = false) String user2Id,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "30") int size) {

        try {
            List<ChatMessage> messages;
            messages = chatMessageService.getChatHistory(user1Id, user2Id, page, size);
            // 优先使用用户ID查询，如果没有则使用用户名
//            if (user1Id != null && user2Id != null) {
//                messages = chatMessageService.getChatHistoryByIds(user1Id, user2Id, page, size);
//            } else if (user1 != null && user2 != null) {
//                messages = chatMessageService.getChatHistory(user1, user2, page, size);
//            } else {
//                return Result.fail("必须提供用户名或用户ID");
//            }

            Map<String, Object> result = new HashMap<>();
            result.put("messages", messages);
            result.put("page", page);
            result.put("size", size);
            result.put("total", messages.size());

            return Result.success(result);
        } catch (Exception e) {
            return Result.fail("获取聊天记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取对话列表
     */
    @GetMapping("/conversations")
    public Result<List<ChatMessage>> getConversations(@RequestParam Integer userId) {
        try {
            List<ChatMessage> conversations = chatMessageService.getConversationList(userId);
            return Result.success(conversations);
        } catch (Exception e) {
            return Result.fail("获取对话列表失败: " + e.getMessage());
        }
    }

    /**
     * 标记消息为已读（基于用户名）
     */
    @PostMapping("/mark-read")
    public Result<String> markAsRead(
            @RequestParam String fromUser,
            @RequestParam String toUser) {

        try {
            chatMessageService.markMessagesAsRead(fromUser, toUser);
            return Result.success("标记成功");
        } catch (Exception e) {
            return Result.fail("标记失败: " + e.getMessage());
        }
    }

    /**
     * 标记消息为已读（基于用户ID）
     */
    @PostMapping("/mark-read-by-ids")
    public Result<String> markAsReadByIds(
            @RequestParam Integer fromUserId,
            @RequestParam Integer toUserId) {

        Logger log = null;
        try {
            log.info("收到标记已读请求 - fromUserId: {}, toUserId: {}", fromUserId, toUserId);

            if (fromUserId == null || toUserId == null) {
                log.warn("参数验证失败 - fromUserId: {}, toUserId: {}", fromUserId, toUserId);
                return Result.fail("用户ID不能为空");
            }

            chatMessageService.markMessagesAsReadByIds(fromUserId, toUserId);
            log.info("标记已读成功 - fromUserId: {}, toUserId: {}", fromUserId, toUserId);
            return Result.success("标记成功");
        } catch (Exception e) {
            log.error("标记已读失败 - fromUserId: {}, toUserId: {}, error: {}", fromUserId, toUserId, e.getMessage(), e);
            return Result.fail("标记失败: " + e.getMessage());
        }
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread-count")
    public Result<Map<String, Object>> getUnreadCount(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Integer userId) {
        try {
            long count;
            Map<String, Object> result = new HashMap<>();

            // 优先使用用户ID查询
            if (userId != null) {
                count = chatMessageService.getUnreadMessageCountById(userId);
                result.put("userId", userId);
            } else if (username != null && !username.trim().isEmpty()) {
                count = chatMessageService.getUnreadMessageCount(username.trim());
                result.put("username", username.trim());
            } else {
                return Result.fail("必须提供用户名或用户ID");
            }

            result.put("count", count);

            return Result.success(result);
        } catch (Exception e) {
            return Result.fail("获取未读数量失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量保存消息
     */
    @PostMapping("/batch-save")
    public Result<Map<String, Object>> batchSaveMessages(@RequestBody List<ChatMessage> messages) {
        try {
            if (messages == null || messages.isEmpty()) {
                return Result.fail("消息列表不能为空");
            }
            
            List<ChatMessage> savedMessages = chatMessageService.saveMessages(messages);
            
            Map<String, Object> result = new HashMap<>();
            result.put("savedCount", savedMessages.size());
            result.put("messages", savedMessages);
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail("批量保存消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 按会话ID获取消息
     */
    @GetMapping("/conversation/{conversationId}")
    public Result<Map<String, Object>> getMessagesByConversationId(
            @PathVariable String conversationId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "30") int size) {
        
        try {
            if (conversationId == null || conversationId.trim().isEmpty()) {
                return Result.fail("会话ID不能为空");
            }
            
            // 解析会话ID获取用户名
            String[] users = conversationId.split("_");
            if (users.length != 2) {
                return Result.fail("无效的会话ID格式");
            }
            
            List<ChatMessage> messages = chatMessageService.getChatHistory(users[0], users[1], page, size);
            
            Map<String, Object> result = new HashMap<>();
            result.put("messages", messages);
            result.put("conversationId", conversationId);
            result.put("page", page);
            result.put("size", size);
            result.put("total", messages.size());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail("获取会话消息失败: " + e.getMessage());
        }
    }

    /**
     * 清空用户的所有聊天记录
     */
    @DeleteMapping("/clear-all")
    public Result<String> clearAllChatMessages(@RequestParam String username) {
        try {
            if (username == null || username.trim().isEmpty()) {
                return Result.fail("用户名不能为空");
            }

            boolean success = chatMessageService.clearAllUserMessages(username.trim());

            if (success) {
                return Result.success("所有聊天记录已清空");
            } else {
                return Result.fail("清空聊天记录失败");
            }
        } catch (Exception e) {
            return Result.fail("清空聊天记录时发生错误: " + e.getMessage());
        }
    }
}